package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.adpter.ChanJianListAdapter;
import com.xn.app.muying.bean.ChanJianListBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 孕期检查
 * Created by Administrator on 2016/10/28.
 */
public class ChanJianListActivity extends BaseActivity {

    //标题栏
    private TextView title = null;
    //返回键
    private ImageView back_img = null;
    //数据显示控件
    private ListView listview = null;
    //有数据页面
    private ScrollView scrollView= null;
    //无数据页面
    private LinearLayout no_data_linearlayout = null;
    //加载框
    AlertDialog dialog;
    //适配器
    private ChanJianListAdapter cjListAdapter = null;
    //保存数据的集合
    private ArrayList<ChanJianListBean> list = new ArrayList<>();
    //数据库对象
    private DBManager db = null;
    //记录得到的数据
    private String data=null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chanjian_list);
        //初始化组件
        initView();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        //初始化数据库对象
        db = new DBManager(this);
        //初始化组件
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        scrollView= (ScrollView) findViewById(R.id.scrollView);
        title = (TextView) findViewById(R.id.title_name);
        back_img = (ImageView) findViewById(R.id.img_back);
        listview = (ListView) findViewById(R.id.listview);
        //设置标题
        title.setText("孕期检查");
        //添加返回事件
        back_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //添加适配器
        cjListAdapter = new ChanJianListAdapter(ChanJianListActivity.this, list);
        listview.setAdapter(cjListAdapter);
        //listview添加点击事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(data!=null&&!data.equals("")&&!data.equals("null")){
                    Intent intent =new Intent(ChanJianListActivity.this,ChanJianDetailActivity.class);
                    intent.putExtra("data",data);
                    intent.putExtra("listItem",position);
                    startActivity(intent);
                }
            }
        });
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(ChanJianListActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            //下载数据
            loadMessage(db.select("antenatalCareHospitalId"));
        } else {
            loginHandler.sendEmptyMessage(2);
        }

    }

    /**
     * 下载数据
     * @param id  医院id
     */
    private void loadMessage(final String id) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.ChanjianList(id)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    data=bodys;
                    if (code == 200 || code == 204) {
                        try {
                            JSONObject jsonObject = new JSONObject(bodys);
                            JSONArray antenatalCares = jsonObject.getJSONArray("antenatalCares");
                            for (int i = 0; i < antenatalCares.length(); i++) {
                                jsonObject = antenatalCares.getJSONObject(i);
                                String id = jsonObject.optString("id");
                                String title = jsonObject.optString("title");
                                String order = jsonObject.optString("order");
                                String keyPoint= jsonObject.optString("keyPoint");
                                String startWeek = jsonObject.optString("startWeek");
                                String endWeek = jsonObject.optString("endWeek");
                                String status = jsonObject.optString("status");
                                //获取必查项目
                                JSONArray requiredItems = jsonObject.getJSONArray("requiredItems");
                                String requiredItemsName = "";
                                for (int a = 0; a < requiredItems.length(); a++) {
                                    jsonObject = requiredItems.getJSONObject(a);
                                    requiredItemsName = requiredItemsName + jsonObject.getString("name");
                                    if (a < requiredItems.length() - 1) {
                                        requiredItemsName = requiredItemsName + ",";
                                    }
                                }
                                //组装数据
                                ChanJianListBean chanJianListBean = new ChanJianListBean();
                                chanJianListBean.setId(id);
                                chanJianListBean.setTitle(title);
                                chanJianListBean.setOrder(order);
                                chanJianListBean.setKeyPoint(keyPoint);
                                chanJianListBean.setStartWeek(startWeek);
                                chanJianListBean.setEndWeek(endWeek);
                                chanJianListBean.setStatus(status);
                                chanJianListBean.setRequiredItemsName(requiredItemsName);
                                list.add(chanJianListBean);
                            }
                            loginHandler.sendEmptyMessage(1);
                        } catch (JSONException e) {
                            loginHandler.sendEmptyMessage(2);
                        }
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    loginHandler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                //数据获取成功
                case 1:
                    scrollView.setVisibility(View.VISIBLE);
                    cjListAdapter.notifyDataSetChanged();
                    setListViewHeightBasedOnChildren(listview);
                    break;
                //数据获取失败
                case 2:
                    no_data_linearlayout.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 动态设置listview高度
     * @param listView   控件
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
